﻿
var _PriceType = "day";
var _Mbid = 0;
var _CodexName = "";
var _isFirstLoad = true;
var _currentBbsid = 0;
var _currentIsMarket = true;

$(function(){

    _Mbid = QueryKeyForPrice();
    _CodexName = decodeURI(QueryKey("codexname"));

    $("#ToBuyCodex").attr("href", "http://www.zyccst.com/yaocai-" + _Mbid + ".html");
    //$("#ToBuyCodex").html("去购买" + _CodexName);

    GetCodexSpec();

 
})

function DayMonthClick(obj)
{
    $(obj).siblings().attr("class", "");
    $(obj).attr("class", "hover");
    _PriceType = $(obj).attr("sign");

    if (_PriceType == "day") {
        $("#divDayChart").show();
        $("#divMonthChart").hide();
    } else {
        $("#divDayChart").hide();
        $("#divMonthChart").show();

        if (_isFirstLoad == true)
        {
            _isFirstLoad = false;
            GetMonthPriceTrend();
        }
    }

}


function GetCodexSpec() {


    ZYCLib.Web.JsonAjax.MvcRequest("/Breeds/GetMCodexPoolListByMBID", { mbid: _Mbid, isMarket: true }, "post", true, false, function (ret) {

        var htmlStr = "";

        for (var i = 0; i < ret.length; i++)
        {
            var item = ret[i];

            htmlStr += "<li class=\"\"><a href='javascript:void()' onclick='GetSpecPriceInfo(" + item.MBSID + ",true,this)' >" + item.MSpec + "</a></li>";

        }


        $("#marketSpec").html(htmlStr);

        //var firstObj = $("#marketSpec li").first().children();
        var firstObj = $("#marketSpec").children(":first").children(":first");

        GetSpecPriceInfo(ret[0].MBSID, true, firstObj);
        GetSpecPriceInfo(ret[0].MBSID, true, firstObj);
    })


    ZYCLib.Web.JsonAjax.MvcRequest("/Breeds/GetMCodexPoolListByMBID", { mbid: _Mbid, isMarket: false }, "post", true, false, function (ret) {

        var htmlStr = "";

        for (var i = 0; i < ret.length; i++) {
            var item = ret[i];

            htmlStr += "<li class=\"\"><a href='javascript:void()' onclick='GetSpecPriceInfo(" + item.MBSID + ",false,this)' >" + item.MSpec + "</a></li>";

        }


        $("#placeSpec").html(htmlStr);

    })


}

function GetSpecPriceInfo(mbsid, isMarket,obj) {

    $("#btnTabDay").attr("class", "hover");
    $("#btnTabMonth").attr("class", "");
    _PriceType = "day";
    $("#divDayChart").show();
    $("#divMonthChart").hide();
   

    _currentBbsid = mbsid;
    _currentIsMarket = isMarket;

    _isFirstLoad = true;

    var specName = $(obj).html();
    $("#CodexSpecName").html(specName);
   

    $(obj).parent().siblings().attr("class", "");
    $(obj).parent().attr("class","hover");

    GetPriceTrend();
    GetSummary();

}



function GetPriceTrend()
{
    //day
    ZYCLib.Web.JsonAjax.MvcRequest("/Breeds/GetPriceTrend", { MBSID: _currentBbsid, IsMarket: _currentIsMarket }, "post", true, false, function (ret) {

        var jsonData = JSON.parse(ret.PriceChartData);

        $('#priceChartContainer').highcharts('StockChart', {

            rangeSelector: GetRangeButtons("day"),
            legend: {
                enabled: true,
                borderWidth: 0,
                y: 0,
                verticalAlign: 'top',
                shadow: false,
                itemMarginBottom: 10,
                itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' },
                itemHiddenStyle: { color: '#999' }
            },
            title: {
                text: ''
            },

            xAxis: {
                labels: {
                    format: "{value:%y-%m-%d}"
                }
            },
            series: jsonData,
            navigator: {
                enabled: true,
                xAxis: {
                    labels: {
                        format: "{value:%Y-%m-%d}"
                    }
                }
            },
            tooltip: {
                crosshairs: true,
                shared: true,
                formatter: function () {

                    var arrHtml = new Array();

                    arrHtml.push('<span style="font-size:10px" class="b">' + Highcharts.dateFormat("%Y-%m-%d", this.x) + '</span><ul class="priceTableC" style="width:230px;">');
                    arrHtml.push("<li class='listTH'><span style=\"width:90px;\">区域</span><span>价格</span>");

                    if (_PriceType == 'day') {
                        arrHtml.push("<span>较上周涨跌</span></li>");
                    }
                    else if (_PriceType == 'month') {
                        arrHtml.push("<span>较上月涨跌</span></li>");
                    }

                    for (var i = 0; i < jsonData.length; i++) {

                        var index = FindIndex(jsonData[i].data, this.x, 0, jsonData[i].data.length - 1);

                        if (index == -1) continue;

                        var weekrate = jsonData[i].data[index][2];
                        var monthrate = jsonData[i].data[index][3];

                        arrHtml.push("<li>");
                        arrHtml.push("<span style=\"width:90px;\">" + jsonData[i].data[index][8].replace('新疆维吾尔', '新疆') + "</span>");
                        arrHtml.push("<span>" + jsonData[i].data[index][1] + "</span>");

                        if (_PriceType == 'day') {

                            if (weekrate > 0) {
                                arrHtml.push("<span><em class=\"up\">" + weekrate + "%</em></span>");
                            } else if (weekrate == 0) {
                                arrHtml.push("<span><em>-</em></span>");
                            } else {
                                arrHtml.push("<span><em class=\"down\">" + weekrate + "%</em></span>");
                            }
                        }
                        else if (_PriceType == 'month') {

                            if (monthrate > 0) {
                                arrHtml.push("<span><em class=\"up\">" + monthrate + "%</em></span>");
                            } else if (weekrate == 0) {
                                arrHtml.push("<span><em>-</em></span>");
                            } else {
                                arrHtml.push("<span><em class=\"down\">" + monthrate + "%</em></span>");
                            }
                        }

                        arrHtml.push("</li>");
                    }

                    arrHtml.push('</ul>');
                    return arrHtml.join('');

                },
                useHTML: true
            }
            , credits: {
                enabled: false
            }



        });



        var series = $('#priceChartContainer').highcharts().series;

        for (var i = 1; i < series.length; i++) {
            series[i].hide();
        }

        CreateDayGrid(jsonData);

    })
}

function GetMonthPriceTrend()
{
    //month
    ZYCLib.Web.JsonAjax.MvcRequest("/Breeds/GetMonthPriceTrend", { MBSID: _currentBbsid, IsMarket: _currentIsMarket }, "post", true, false, function (ret) {

        var jsonData = JSON.parse(ret.PriceChartData);

        $('#priceMonthChartContainer').highcharts('StockChart', {

            rangeSelector: GetRangeButtons("month"),
            legend: {
                enabled: true,
                borderWidth: 0,
                y: 0,
                verticalAlign: 'top',
                shadow: false,
                itemMarginBottom: 10,
                itemStyle: { cursor: 'pointer', color: '#274b6d', fontSize: '12px' },
                itemHiddenStyle: { color: '#999' }
            },
            title: {
                text: ''
            },

            xAxis: {
                labels: {
                    format: "{value:%y-%m-%d}"
                }
            },
            series: jsonData,
            navigator: { enabled: true },
            tooltip: {
                crosshairs: true,
                shared: true,
                formatter: function () {

                    var arrHtml = new Array();

                    arrHtml.push('<span style="font-size:10px" class="b">' + Highcharts.dateFormat("%Y-%m-%d", this.x) + '</span><ul class="priceTableC" style="width:230px;">');
                    arrHtml.push("<li class='listTH'><span style=\"width:90px;\">区域</span><span>价格</span>");

                    if (_PriceType == 'day') {
                        arrHtml.push("<span>较上周涨跌</span></li>");
                    }
                    else if (_PriceType == 'month') {
                        arrHtml.push("<span>较上月涨跌</span></li>");
                    }

                    for (var i = 0; i < jsonData.length; i++) {

                        var index = FindIndex(jsonData[i].data, this.x, 0, jsonData[i].data.length - 1);

                        if (index == -1) continue;

                        var weekrate = jsonData[i].data[index][2];
                        var monthrate = jsonData[i].data[index][3];

                        arrHtml.push("<li>");
                        arrHtml.push("<span style=\"width:90px;\">" + jsonData[i].data[index][8].replace('新疆维吾尔', '新疆') + "</span>");
                        arrHtml.push("<span>" + jsonData[i].data[index][1] + "</span>");

                        if (_PriceType == 'day') {

                            if (weekrate > 0) {
                                arrHtml.push("<span><em class=\"up\">" + weekrate + "%</em></span>");
                            } else if (weekrate == 0) {
                                arrHtml.push("<span><em>-</em></span>");
                            } else {
                                arrHtml.push("<span><em class=\"down\">" + weekrate + "%</em></span>");
                            }
                        }
                        else if (_PriceType == 'month') {

                            if (monthrate > 0) {
                                arrHtml.push("<span><em class=\"up\">" + monthrate + "%</em></span>");
                            } else if (weekrate == 0) {
                                arrHtml.push("<span><em>-</em></span>");
                            } else {
                                arrHtml.push("<span><em class=\"down\">" + monthrate + "%</em></span>");
                            }
                        }

                        arrHtml.push("</li>");
                    }

                    arrHtml.push('</ul>');
                    return arrHtml.join('');

                },
                useHTML: true
            }
            , credits: {
                enabled: false
            }



        });


        var series = $('#priceMonthChartContainer').highcharts().series;

        for (var i = 1; i < series.length; i++) {
            series[i].hide();
        }

        CreateMonthGrid(jsonData);
    })
}

function GetSummary()
{
    //summary
    ZYCLib.Web.JsonAjax.MvcRequest("/Breeds/GetMSpecPriceHighLowByMBSID", { MBSID: _currentBbsid, AreaType: _currentIsMarket == true ? 1 : 2 }, "post", true, false, function (ret) {

        var jsondata = ret;

        var todayStr = "日&nbsp;期：" + jsondata.TodayTime ;

        $('#spanToday').html(todayStr);
        $('#emTodayPrice').html(jsondata.TodayPrice);

        $('#emDiffYesterdayAmount').html(getshowvalue(false, jsondata.DiffYesterdayAmount, true));
        $('#emDiffYesterdayAmount').attr("class", getclass(jsondata.DiffYesterdayAmount, true));

        $('#emDiffYesterdayRate').html(getshowvalue(true, jsondata.DiffYesterdayRate, true));
        $('#emDiffYesterdayRate').attr("class", getclass(jsondata.DiffYesterdayRate, true));

        $('#emHighLatestMonth').html(getshowvalue(false, jsondata.HighLatestMonth));
        $('#emHighLatestMonth').attr("class", getclass(jsondata.HighLatestMonth));

        $('#emLowLatestMonth').html(getshowvalue(false, jsondata.LowLatestMonth));
        $('#emLowLatestMonth').attr("class", getclass(jsondata.LowLatestMonth));

        $('#emHighLatestHalfYear').html(getshowvalue(false, jsondata.HighLatestHalfYear));
        $('#emHighLatestHalfYear').attr("class", getclass(jsondata.HighLatestHalfYear));

        $('#emLowLatestHalfYear').html(getshowvalue(false, jsondata.LowLatestHalfYear));
        $('#emLowLatestHalfYear').attr("class", getclass(jsondata.LowLatestHalfYear));

        $('#emHighLatestYear').html(getshowvalue(false, jsondata.HighLatestYear));
        $('#emHighLatestYear').attr("class", getclass(jsondata.HighLatestYear));

        $('#emLowLatestYear').html(getshowvalue(false, jsondata.LowLatestYear));
        $('#emLowLatestYear').attr("class", getclass(jsondata.LowLatestYear));
        
    })
}

function getclass(value, isDiff) {
    if (isDiff) {
        return value > 0 ? "red" : "green";
    } else {
        return "";
    }
}

function getshowvalue(isRate, value, isDiff) {
    var result = "-";
    if (value == 0) {
        result = "-";
    }
    if (value > 0) {
        result = isRate ? ("+" + value + "%") : (isDiff ? "+" : "") + value.toString();
    }
    if (value < 0) {
        result = isRate ? +value + "%" : value;
    }
    return result;
}

function FindIndex(arrData, number, startPos, endPos) {

    if (startPos == endPos) return startPos;
    var min = arrData[startPos][0];
    var max = arrData[endPos][0];
    if (min >= max) return -1;
    var midIdx = startPos + parseInt((endPos - startPos) / 2);
    var mid = arrData[midIdx][0];

    if (number == mid) return midIdx;
    if (number == min) return startPos;
    if (number == max) return endPos;

    if (number > min && number < mid)
        return FindIndex(arrData, number, startPos, midIdx);
    if (number > mid && number < max)
        return FindIndex(arrData, number, midIdx, endPos);

    return -1;
};


function GetRangeButtons(obj) {

    var rangebutton = [];
    var index = 0;

    if (obj == "day") {

        rangebutton = [{
            type: 'month',
            count: 1,
            text: '1月'
        }, {
            type: 'month',
            count: 3,
            text: '3月'
        }, {
            type: 'month',
            count: 6,
            text: '6月'
        },
        {
            type: 'all',
            text: '全部'
        }];

        index = 3;
    }

    if (obj == "month") {
        rangebutton = [

            {
                type: 'month',
                count: 6,
                text: '6月'
            },

            {
                type: 'all',
                text: '全部'
            }];
        index = 1;
    }

    return {
        inputDateFormat: "%Y-%m-%d",
        allButtonsEnabled: true,
        buttons: rangebutton,       
        buttonTheme: { 
            fill: '#f7f7f7',
            stroke: 'none',
            'stroke-width': 0,
            r: 8,
            style: {
                color: 'black',
                fontWeight: 'normal'
            },
            states: {
                select: {
                    fill: '#f7f7f7',
                    style: {
                        color: 'black',
                        fontWeight: 'bold'
                    }
                }
            }
        },
        selected: index
    };

}

function CreateDayGrid(chartData) {

    $("#priceWeekContentTab").html("");
    $("#priceWeekContentCon").html("");

    for (var i = 0; i < chartData.length; i++) {

        var oneChart = chartData[i];

        var nameClass = ""
        var contentClass = "";

        if (i == 0) {
            nameClass = "hover";
        } else {
            contentClass = "none";
        }
        
        //name
        var nameStr = "<li class='" + nameClass + "'>" + oneChart.name + "</li>";

        $("#priceWeekContentTab").append(nameStr);

        //content and page
        var paramObj = {};

        eval("_pageHanderDay" + i + " = new PageHander();");

        paramObj.pageHanderObj = eval("_pageHanderDay" + i + "");
        paramObj.pageHanderName = "_pageHanderDay" + i;

        var htmlStr = "<div sign='pricediv' class='" + contentClass + "' >";
        htmlStr += "     <ul id='priceContentDay" + i + "' class=\"priceTableA\"></ul>";
        htmlStr += "     <div id='pageContainerDay" + i + "'></div>"
        htmlStr += "  </div>";

        $("#priceWeekContentCon").append(htmlStr);

        paramObj.pageContainerId = "pageContainerDay" + i;
        paramObj.priceContentId = "priceContentDay" + i;
        paramObj.dataObj = oneChart.data;
        paramObj.priceType = "day";

        PriceTable(paramObj);
    }

    $("#priceWeekContentTab li").click(function () {

        $(this).siblings().attr("class", "");
        $(this).attr("class", "hover");
        var index = $(this).index();

        $("#priceWeekContentCon div[sign=pricediv]").attr("class","none");
        $($("#priceWeekContentCon div[sign=pricediv]")[index]).attr("class", "");

    });

}

function CreateMonthGrid(chartData) {

    $("#priceMonthContentTab").html("");
    $("#priceMonthContentCon").html("");

    for (var i = 0; i < chartData.length; i++) {

        var oneChart = chartData[i];

        var nameClass = ""
        var contentClass = "";

        if (i == 0) {
            nameClass = "hover";
        } else {
            contentClass = "none";
        }

        //name
        var nameStr = "<li class='" + nameClass + "'>" + oneChart.name + "</li>";

        $("#priceMonthContentTab").append(nameStr);

        //content and page
        var paramObj = {};

        eval("_pageHanderMonth" + i + " = new PageHander();");

        paramObj.pageHanderObj = eval("_pageHanderMonth" + i + "");
        paramObj.pageHanderName = "_pageHanderMonth" + i;

        var htmlStr = "<div sign='pricediv' class='" + contentClass + "' >";
        htmlStr += "     <ul id='priceContentMonth" + i + "' class=\"priceTableB\"></ul>";
        htmlStr += "     <div id='pageContainerMonth" + i + "'></div>"
        htmlStr += "  </div>";

        $("#priceMonthContentCon").append(htmlStr);

        paramObj.pageContainerId = "pageContainerMonth" + i;
        paramObj.priceContentId = "priceContentMonth" + i;
        paramObj.dataObj = oneChart.data;
        paramObj.priceType = "month";

        PriceTable(paramObj);
    }

    $("#priceMonthContentTab li").click(function () {

        $(this).siblings().attr("class", "");
        $(this).attr("class", "hover");
        var index = $(this).index();

        $("#priceMonthContentCon div[sign=pricediv]").attr("class", "none");
        $($("#priceMonthContentCon div[sign=pricediv]")[index]).attr("class", "");

    });

}

function PriceTable(paramObj) {

    var skipCount = paramObj.pageHanderObj.PageSize * (paramObj.pageHanderObj.PageNo - 1);

    var beginIndex = paramObj.dataObj.length - 1 - skipCount;
    var endIndex = beginIndex - paramObj.pageHanderObj.PageSize;

    var arrHtml = new Array();

    arrHtml.push("<li class=\"listTH\">");
    arrHtml.push("<span>日期</span>");
    arrHtml.push("<span>规格</span>");
    arrHtml.push("<span>价格</span>");

    if (paramObj.priceType == 'day') {
        arrHtml.push("<span>较上周涨跌</span>");
    }

    arrHtml.push("<span>较上月涨跌</span>");
    arrHtml.push("<span>较去年幅度</span>");
    arrHtml.push("<span>走势</span>");
    arrHtml.push("</li>");

    for (var i = beginIndex; i > endIndex && i >= 0; i--) {


        var weekRate = paramObj.dataObj[i][2];
        var monthRate = paramObj.dataObj[i][3];
        var yearRate = paramObj.dataObj[i][4];
        var date;
        if (paramObj.priceType != 'day') {
            date = paramObj.dataObj[i][9].substr(0, 7);
        } else { date = paramObj.dataObj[i][9]; }
        arrHtml.push("<li>");
        arrHtml.push("<span>" + date + "</span>");
        arrHtml.push("<span>" + paramObj.dataObj[i][6] + "</span>");
        arrHtml.push("<span><em>" + paramObj.dataObj[i][1] + "</em></span>");

        if (paramObj.priceType == 'day') {
            if (weekRate > 0) {
                arrHtml.push("<span><em class=\"up\">" + weekRate + "%</em></span>");
            } else if (weekRate == 0) {
                arrHtml.push("<span><em>-</em></span>");
            } else {
                arrHtml.push("<span><em class=\"down\">" + weekRate + "%</em></span>");
            }
        }

        if (monthRate > 0) {
            arrHtml.push("<span><em class=\"up\">" + monthRate + "%</em></span>");
        } else if (monthRate == 0) {
            arrHtml.push("<span><em>-</em></span>");
        } else {
            arrHtml.push("<span><em class=\"down\">" + monthRate + "%</em></span>");
        }

        if (yearRate > 0) {
            arrHtml.push("<span><em class=\"up\">" + yearRate + "%</em></span>");
        } else if (yearRate == 0) {
            arrHtml.push("<span><em>-</em></span>");
        } else {
            arrHtml.push("<span><em class=\"down\">" + yearRate + "%</em></span>");
        }

        arrHtml.push("<span>" + paramObj.dataObj[i][10] + "</span>");
        arrHtml.push("</li>");


    }

    $("#" + paramObj.priceContentId + "").html(arrHtml.join(''));

    paramObj.pageHanderObj.ShowPage(paramObj.pageHanderName, paramObj.pageContainerId, PriceTable, paramObj.dataObj.length, paramObj);


}




